package com.example.springboot.controller;

import org.apache.commons.io.FilenameUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * 学生简历上传Controller
 *
 * @author 柏旭东
 * @date 2024-6-20
 */

@CrossOrigin(origins = "http://localhost:7070")
@RestController
@RequestMapping("/Resume")
public class ResumeUploadController {

    //简历上传路径
    private static final String RESUME_DIR = "/path/to/resume/directory";//路径要修改

    // 文件大小限制，例如：10MB
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    // 允许的文件扩展名
    private Set<String> allowedExtensions = new HashSet<>(Arrays.asList("pdf", "doc", "docx", "odt"));

    /**
     *
     * 上传学生简历
     */
    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("resume") MultipartFile file) {
        if (file.isEmpty() || file.getSize() > MAX_FILE_SIZE) {
            return ResponseEntity.badRequest().body("上传失败：文件太大或为空。");
        }
        String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase();
        if (!allowedExtensions.contains(fileExtension)) {
            return ResponseEntity.badRequest().body("上传失败：不支持的文件类型。");
        }

        try {
            // 生成安全的文件名，例如使用UUID
            String safeFilename = generateSafeFilename(file.getOriginalFilename());
            File dir = new File(RESUME_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File resumeFile = new File(dir, safeFilename);

            file.transferTo(resumeFile);
            return ResponseEntity.ok("简历上传成功！");
        } catch (IOException e) {
//             记录日志
//             log.error("Resume upload failed", e);
            return ResponseEntity.internalServerError().body("简历上传失败：服务器错误。");
        }
    }

    // 生成安全的文件名的方法
    private String generateSafeFilename(String originalFilename) {
        // 使用UUID或其他方法来生成安全的文件名
        String baseName = new File(originalFilename).getName();
        String safeName = UUID.randomUUID().toString();
        return safeName + "." + FilenameUtils.getExtension(baseName);
    }


}
